<?php
/**
 * Kbs
 *
 * Project index
 * php version : 5.2.6
 *
 * @author      kim
 * @version     2.0
 */

define('START_TIME', microtime(true));

/**
 * Php version checking
 *
 */
if (true === version_compare(phpversion(), '5.2.4', '<')) {
    exit('Boot failure ! (102)');
}

/**
 * Define path to project root
 *
 */
defined('PROJECT_ROOT')
    || define('PROJECT_ROOT',
              realpath(dirname(dirname(__FILE__))));

/**
 * Define path to application directory
 *
 */
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH',
              PROJECT_ROOT . '/application');

/**
 * Define application environment
 *
 */
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV',
              (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV')
                                         : 'production'));

/**
 * Set include paths
 *
 * Typically, you will also want to add your library/ directory
 * to the include_path, particularly if it contains your ZF install
 */
set_include_path(implode(PATH_SEPARATOR, array(
    PROJECT_ROOT . '/library',
    'F:\www\zendframework\zendframework\library'
    //get_include_path()
    //PROJECT_ROOT . '/library/PEAR',
)));

/**
 * Config file inc
 *
 * Caching file
 */
defined('CONFIG_INC')
    || define('CONFIG_INC',
              PROJECT_ROOT . '/library/Kbs/Config/Application.ini.inc');

/**
 * If no cache we use the default ini
 *
 */
$configFile = CONFIG_INC;
$noConfigCache = false;
if (false == is_file(CONFIG_INC)) {
    $configFile = PROJECT_ROOT . '/library/Kbs/Config/Application.ini';
    $noConfigCache = true;
}

/**
 * Zend_Application
 *
 */
require_once 'Zend/Application.php';

/**
 * Create application
 *
 */
$application = new Zend_Application(
    APPLICATION_ENV,
    $configFile
);

/**
 * If no config cache then we create it
 *
 * Only for production
 */
if ($noConfigCache and ('production' == APPLICATION_ENV)) {
    $configs = '<?php' . PHP_EOL
             . 'return '
             . var_export($application->getOptions(), true) . PHP_EOL
             . '?>';
    file_put_contents(CONFIG_INC, $configs);
} else {
    // Debug
    //echo 'The configs are cached';
}

umask(0);

/**
 * Bootstrap and Run
 *
 */
try {
    /**
     * We need to know the warnings when develop
     *
     */
    if ('production' !== APPLICATION_ENV) {
        $application->getAutoloader()->suppressNotFoundWarnings(false);
    }


    /**
     * Oracle
     */
    /*
    $application->getBootstrap()->bootstrap('Db');
    $db = $application->getBootstrap()->getResource('Db');
    $db->getConnection();

    $data = array(
        ':ID' => '1',
        ':NAME' => 'aa',
        ':TEXT_CLOB' => 'ccccccccc',
        ':TEXT_BLOB' => 'bbbbbbbbb',
    );

    $sql = 'INSERT INTO TESTUSER (ID,NAME,TEXT_CLOB,TEXT_BLOB) VALUES (:ID,:NAME,:TEXT_CLOB,:TEXT_BLOB)';
    $stmt = new Zend_Db_Statement_Oracle($db, $sql);
    $result = $stmt->execute($data);

    if ($result) {
        $tu = $db->fetchAll("SELECT * FROM TESTUSER");
        var_dump($tu);
    }

    die;
    */


    /**
     * curl
     *
     */
    /*
    $ch = curl_init("http://www.kimbs-local.info/");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1 );
    curl_setopt($ch, CURLOPT_HTTPHEADER,array(
        'Accept-Language: zh-CN',
    ));
    curl_setopt($ch, CURLOPT_POST, 1 );
    $result = curl_exec($ch);
    curl_close($ch);
    echo $result;
    */



    /**
     * For Pear
     *
     */
    /*
    $application->getAutoloader()->setFallbackAutoloader(true);
    $workbook = new Spreadsheet_Excel_Writer();
    var_dump($workbook);die;
    */


    /**
     * We only boot Front Controller and leave others loaded on demand
     *
     */
    $application->getBootstrap()->bootstrap('FrontController');
    $application->getBootstrap()->bootstrap('Router');
    $application->getBootstrap()->bootstrap('Locale');
    $application->run();

    /**
     * Debug
     */
    //var_dump($application->getBootstrap());

    /**
     * The time spent
     *
     */
    if (APPLICATION_ENV != 'production') {
        echo number_format(microtime(true) - START_TIME, 8, '.', '');
    }

} catch (Exception $e) {

    /*
    if (!include_once(PROJECT_ROOT . '/error/500.html')) {
        @header("HTTP/1.x 500 Internal Server Error");
        @header('Status: 500 Internal Server Error');
    }
    */

    /**
     * Handle all errors by 404
     *
     */
    if (!include_once(PROJECT_ROOT . '/error/404.html')) {
        @header('HTTP/1.x 404 Not Found');
        @header('Status: 404 Not Found');
    }

    $errorMessage = get_class($e);

    if ($e->getCode()) {
        $errorMessage .= ' (' . $e->getCode() . ') ';
    }

    $errorMessage .= PHP_EOL . $e->getMessage() . PHP_EOL
                   . $e->getTraceAsString() . PHP_EOL
                   . PHP_EOL;

    if (APPLICATION_ENV != 'production') {

        echo nl2br(print_r($errorMessage, true));

    } else {
        $logFile = PROJECT_ROOT . '/repository/logs/' . date('Y-m-d') . '.log';

        if (file_exists($logFile)) {
            $writer = new Zend_Log_Writer_Stream($logFile, 'w');
        } else {
            $writer = new Zend_Log_Writer_Stream($logFile, 'a');
        }

        $logger = new Zend_Log();
        $logger->addWriter($writer);
        $logger->log($errorMessage, Zend_Log::DEBUG);
    }

    exit;
}